package com.samphanie.auiu.auth.controller;

import com.samphanie.auiu.auth.security.properties.AuthProperties;
import com.samphanie.auiu.auth.validation.code.captcha.Captcha;
import com.samphanie.auiu.auth.validation.code.captcha.ValidateCodeProcessorHolder;
import com.samphanie.auiu.auth.validation.code.captcha.enums.ValidateCodeType;
import com.samphanie.auiu.common.exception.ApiException;
import com.samphanie.auiu.common.utils.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Api(tags = "验证码")
@RestController
@RequestMapping(AuthProperties.DEFAULT_VALIDATE_CODE_URL_PREFIX)
@RequiredArgsConstructor
public class ValidateCodeController {

    private final ValidateCodeProcessorHolder validateCodeProcessorHolder;
    private final HttpServletRequest request;
    private final HttpServletResponse response;

    /**
     * 创建验证码，根据验证码类型不同，调用不同的 {@link Captcha}接口实现
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "验证码类型：sms | image", paramType = "path", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "deviceId", value = "唯一标识：客户端ID+用户设备码", paramType = "header", dataTypeClass = String.class, required = true)
    })
    @ApiOperation("发送验证码")
    @GetMapping("/{type}")
    public void createCode(@PathVariable String type) throws Exception {
        validateCodeProcessorHolder.findValidateCodeProcessor(type)
                .render(new ServletWebRequest(request, response));
    }

    /**
     * 创建图片验证码
     */
    @GetMapping("/getImageCode")
    public void getImageCode() {
        try {
            String type = ValidateCodeType.IMAGE.name().toLowerCase();
            validateCodeProcessorHolder.findValidateCodeProcessor(type)
                    .render(new ServletWebRequest(request, response));
            System.out.println(response.getOutputStream().toString());
        } catch (Exception e) {
            throw new ApiException(ResultCode.INTERNAL_SERVER_ERROR);
        }
    }

}
